<template>
    <div class="loginDiv">
        <div id="loginBack">
            <img id="backlogo" src="../../assets/images/login_bg.png"/>
        </div>
        <div class="loginForm">
            <el-tabs type="card"  v-model="activeName">
                <el-tab-pane label="用户登录" name="userlogin" >
                    <el-form ref="form"  label-width="100px">
                        <el-form-item label="用户名">
                            <el-input v-model="loginUser.identify" placeholder="请输入注册手机/邮箱/账号"></el-input>
                        </el-form-item>
                        <el-form-item label="密码">
                            <el-input v-model="loginUser.password" placeholder="请输入密码" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="" style="margin-bottom: 0px">
                            <hua-kuai @verify='verify' @refresh='refresh'></hua-kuai>
                            记住我<el-switch
                                    v-model="rememberme"
                                    active-color="#13ce66"
                                    inactive-color="#ff4949">
                            </el-switch>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button style="width: 80%; display: block" @click="doLogin" type="primary" plain>登录</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>
                <el-tab-pane label="用户注册" name="userreg">
                    <el-form ref="form"  label-width="100px">
                        <el-form-item label="用户名">
                            <el-input v-model="regUser.identify" placeholder="请输入注册手机/邮箱"></el-input>
                        </el-form-item>
                        <el-form-item label="">
                            <!--
                            <el-button>发送验证码</el-button>
                            -->
                            <img :src="randomCodeImgUrl" title="看不清楚，换一张" style="cursor:pointer" @click="changeRandomCodeImg">
                        </el-form-item>
                        <el-form-item label="密码">
                            <el-input v-model="regUser.password" placeholder="请输入密码" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="确认密码">
                            <el-input v-model="regUser.confirmpass" placeholder="请输入确认密码" show-password></el-input>
                        </el-form-item>
                        <el-form-item label="验证码">
                            <el-input v-model="regUser.validateCode" placeholder="请输入验证码"></el-input>
                        </el-form-item>
                        <el-form-item label="">
                            <el-button style="width: 80%; display: block" type="success" @click="doReg" plain>注册</el-button>
                        </el-form-item>
                    </el-form>
                </el-tab-pane>

            </el-tabs>
        </div>
    </div>
</template>

<script>

    import request from "@/util/request";
    import graceChecker from '@/util/graceChecker';
    import myCookie from '@/util/myCookie';
    let jwt = require("jsonwebtoken");

    export default {
        name: "MyLogin",
        data(){
            return{
                rememberme: true,
                regRandomCodeToken:jwt.sign({data:new Date().getMilliseconds()},'myshopping.com',{expiresIn:6000*30}),
                activeName: "userlogin",
                huakuaiFlag: false, //默认滑块验证失败
                randomCodeImgUrl:'/api/commons/randomCode?tm='+new Date().getMilliseconds(),
                loginUser:{
                    identify:'',
                    password:''
                },
                regUser:{
                    identify:"", //输入的电子邮箱或者手机号码
                    email:"",
                    mobile:"",
                    password:"",
                    confirmpass:"",
                    validateCode:"",
                    flag: 1
                }
            }
        },
        mounted(){
            this.randomCodeImgUrl =  '/api/commons/randomCode?tm='+new Date().getMilliseconds()+"&token="+this.regRandomCodeToken;
            //初始化登录的账号。
            myCookie.getCookie(this.loginUser);
        },
        methods:{
            verify(result){
                console.log(result) // result为true表示验证通过，false表示验证三次都失败了哦
                this.huakuaiFlag = result;
            },
            refresh(){
                console.log('用户点击了初始化')
            },

            changeRandomCodeImg(){
               this.randomCodeImgUrl = '/api/commons/randomCode?tm='+new Date().getMilliseconds()+"&token="+this.regRandomCodeToken;
            },

            goToWelcomePage(){
                this.$router.push('/');
            },
            //用户登录
            doLogin(){
                console.log('执行用户登录....');

                //先检查滑块验证的状态是不是true
                if(!this.huakuaiFlag){
                    this.$message({
                        message: '滑块验证失败！',
                        type: 'error'
                    });
                    return;
                }

                //以下是使用mock测试
                //测试post mock测试
                /*
                request.post('/api/login',{
                    username:'admin',
                    password:'123456'
                }).then(resp=>{
                    console.log(resp);
                }).catch(err=>{
                    console.log(err);
                })*/

                //测试mock get请求
                /*
                request.get('/api/login',{
                    params:{
                        username: 'admin',
                        password: '88888'
                    }
                }).then(resp=>{
                    console.log(resp);
                }).catch(err=>{
                    console.log(err);
                })*/


                //以下调用真正的后端接口实现的用户登录请求
                //使用axios发送异步请求，调用服务器接口。测试一下。

                request.get('/api/users/auth',{
                    params:{
                        identify: this.loginUser.identify,
                        password: this.loginUser.password
                    }
                }).then(resp=>{
                    console.log(resp);
                    if(resp.status===200){
                        this.$message({
                            message: '登录成功！',
                            type: 'success'
                        });
                        console.log("登录成功之后返回的用户对象....");
                        console.log(resp.data);
                        //把登录成功用户对象保存到本地缓存里面。前端的缓存。
                        window.localStorage.setItem("myshoppingdemo",JSON.stringify(resp.data));
                        //判断一下用户是否需要记住我
                        if(this.rememberme){
                            myCookie.setCookie(this.loginUser.identify,this.loginUser.password,100);
                        }else{
                            myCookie.clearCookie(); //请求用户名和密码
                        }

                        setTimeout(this.goToWelcomePage(),2000);
                    }else{
                        this.$message({
                            message: '登录失败,请检查用户名或者密码是否正确！',
                            type: 'error'
                        });
                    }
                }).catch(err=>{
                    console.log(err);
                })
            },

            changeTab(activeName){
                console.log('切换tab....,activeName='+activeName);
                this.activeName = activeName;
                console.log("this.activeName:"+this.activeName);

            },

            //用户注册
            doReg(){
                console.log('执行用户注册....');

                //判断一下identify究竟是电子邮箱还是手机号码
                if(graceChecker.check(this.regUser.identify,"email")){
                    this.regUser.email = this.regUser.identify;
                    this.regUser.mobile = "";
                }else if(graceChecker.check(this.regUser.identify,"phoneno")){
                    this.regUser.mobile = this.regUser.identify;
                    this.regUser.email = "";
                }else{
                    this.$message({
                        message: '输入数据非法！',
                        type: 'error'
                    });
                    return;
                }

                if(this.regUser.password.length<6){
                    this.$message({
                        message: '密码长度不能小于6位！',
                        type: 'error'
                    });
                    return;
                }
                if(this.regUser.password!=this.regUser.confirmpass){
                    this.$message({
                        message: '确认密码与密码不同！',
                        type: 'error'
                    });
                    return;
                }

                console.log("注册用户资料是："+JSON.stringify(this.regUser));


                //使用axios发送异步请求，调用服务器接口。测试一下。
                request.post('/api/users/',this.regUser,{
                    params:{
                        token: this.regRandomCodeToken
                    }
                }).then(resp=>{
                    console.log(resp);
                    if(resp.status===200){
                        this.$message({
                            message: '注册成功！',
                            type: 'success'
                        });

                        //注册成功之后自动切换到登录的tab;
                        setTimeout(this.changeTab('userlogin'),2000);

                    }else if(resp.status==205)
                    {
                        this.$message({
                            message: '验证码不正确！',
                            type: 'error'
                        });
                    }
                    else{
                        this.$message({
                            message: '注册失败！',
                            type: 'error'
                        });
                    }
                }).catch(err=>{
                    console.log(err);
                })
            }
        }
    }
</script>

<style scoped>
    .loginDiv{
        width: 100%;
        height: 520px;
        margin: 0px auto;
        background: rgb(34, 119, 223);
        display: flex;
        justify-content: space-around;
    }
    #backlogo {
        margin: 40px 0 0 0px;

    }

    .loginForm{
        margin: 20px;
        background: #FFFFFF;
        width: 480px;
        border-radius: 0px;
    }
    .el-tabs{
        background: #FFFFFF;
    }
    .el-tab-pane{
        background: #FFFFFF;
    }
    .el-input{
        width: 280px;
    }
</style>